import React, {useState, useRef} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {queryRule, getPayOrder, repIntegra} from './service';
import {money_trans} from '@/utils/utils';
import OrderCommon from '@/pages/OrderCommon';
import CreateForm from './components/CreateForm';
import {DatePicker, Descriptions, Divider, Image, Input, message, Radio, Select} from 'antd';
import {useEffect} from 'react';
import Moment from 'moment';
import {getMember} from "@/pages/VipManagement/VipModule/service";
import styles from "@/global.less";
import Access from '@/components/Access/Access';
const dateFormat = 'YYYY/MM/DD';
const TableList = (props) => {
  const [payOrderValues, setPayOrderValues] = useState({});

  const [repIntegralVisible, handleRepIntegralVisible] = useState(false);
  const [repIntegralValues, setRepIntegralValues] = useState({});
  const [memberState, setMemberState] = useState(false);
  const [memberValue, setMemberValue] = useState({});
  const [currentIntegralAccountMoney, setCurrentIntegralAccountMoney] = useState();
  const [currentIntegralTime, setCurrentIntegralTime] = useState();
  const [order, setOrder] = useState(false);
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [memberNum, setMemberNum] = useState();
  /** 国际化配置 */
  const handlePay = (params) => {
    getPayOrder(params).then((res) => {
      const {code, data} = res;
      code === 0 ? (setPayOrderValues(data), setOrder(true)) : null;
    });
  };
  const handleMember = (payload) => {
    getMember(payload).then((res) => {
      const {code, data} = res;
      code === 0 ? setMemberValue(data) : message.error('错误！');
    });
  };
  useEffect(() => {
    const {query} = props.history.location;
    setTimeout(() => {
      return query?.cardNum ? setMemberNum(query?.cardNum) : setMemberNum();
    }, 0);
    actionRef.current.reload();
  }, [props.history.location.query?.cardNum]);
  const repIntegralColumns = [

    {
      title: '姓名',
      dataIndex: 'name',
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <Input disabled value={repIntegralValues.memberName}/>;
      },
    },
    {
      title: '余额',
      dataIndex: 'money',
      valueType: 'money',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '余额为必填项',
          },
        ],
      },
    },

    {
      title: '开始时间',
      dataIndex: 'startTime',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '开始时间为必填项',
          },
        ],
      },
      render: (_, record) => {
        return (
          <span>{record.birthday ? new Date(record.startTime).toLocaleDateString() : null}</span>
        );
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <DatePicker format={dateFormat} style={{width: '100%'}}/>;
      },
    },

    {
      title: '结束时间',
      dataIndex: 'endTime',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '结束时间为必填项',
          },
        ],
      },
      render: (_, record) => {
        return (
          <span>{record.birthday ? new Date(record.endTime).toLocaleDateString() : null}</span>
        );
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return <DatePicker format={dateFormat} style={{width: '100%'}}/>;
      },
    },

  ];
  const columns = [
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      renderFormItem: () => {
        return <Input allowClear onChange={(e) => setMemberNum(e.target.value)}/>;
      },
    },
    {
      title: '会员名',
      dataIndex: 'memberName',
      render: (dom, entity) => {
        return <a
          onClick={() => {
            console.log(entity);
            setRepIntegralValues(entity);
            handleRepIntegralVisible(true);
          }}
        >{dom}</a>;
      },
      hideInSearch: true,
    },
    {
      title: '会员手机号',
      dataIndex: 'memberMobile',
      hideInSearch: true,
    },

    {
      title: '应返积分',
      dataIndex: 'integral',

      hideInSearch: true,
    },
    // {
    //   title: '赠送比例',
    //   dataIndex: 'scale',
    //   hideInSearch: true,
    //   render: (dom) => {
    //     return <div>{dom}%</div>;
    //   },
    // },
    {
      title: '积分来源',
      dataIndex: 'type',

      valueEnum: {
        2: {
          text: '余额',
          status: 'Processing',
        },
        1: {
          text: '消费',
          status: 'Success',
        },
        3: {
          text: '补偿',
          status: 'Error',
        },
      },
    },
    {
      title: '是否到账',
      dataIndex: 'returnType',
      valueEnum: {
        true: {
          text: '已到账',
          status: 'Processing',
        },
        false: {
          text: '未到账',
          status: 'Error',
        },
      },
    },
    {
      title: '是否取消',
      dataIndex: 'cancel',
      valueEnum: {
        true: {
          text: '已取消',
          status: 'Error',
        },
        false: {
          text: '未取消',
          status: 'Processing',
        },
      },
    },
    {
      title: '赠送日期',
      dataIndex: 'currentDate',
      hideInSearch: true,
      valueType: 'date',
      render: (_, record) => {
        return <span>{record.type === 1 ? Moment(record.currentDate).format('yyyy-MM') : Moment(record.currentDate).format('YYYY-MM-DD')}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {

        return <Access accessKey={"@seeIntegralRecordDetail"}>
          <a
            onClick={() => {
              if (record.type === 1) {
                handlePay(record.billId);
                setOrder(true);
              } else {
                setCurrentIntegralTime(Moment(record.createTime).format('YYYY-MM-DD HH:mm:ss'));
                setCurrentIntegralAccountMoney(record.integralMoney);
                handleMember(record.memberId);
                setMemberState(true);
              }
            }}
          >
            {record.type === 1 ? "查看订单详情" : "查看积分详情"}
          </a>
        </Access>;

      }
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="每日积分赠送明细记录"
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={false}
        request={(params, sorter, filter) =>
          queryRule({...params, sorter, filter, memberNumber: memberNum})
        }
        onReset={(params) => {
          props.history.replace({cardNum: ''}, props.history.location);
          setMemberNum();
          actionRef.current.reload();
        }}
        postData={(params) => {
          const {list, total} = params;

          //message.success(`${props.history.location.query.cardNum || ''}积分记录查询成功!`);
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 24,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
      <CreateForm
        title={'订单详情'}
        width={1300}
        onCancel={() => setOrder(false)}
        modalVisible={order}
      >
        <OrderCommon
          payOrderValues={payOrderValues}
          refund={false}
        />
      </CreateForm>
      <CreateForm
        width={800}
        onCancel={() => {
          setMemberState(false);
        }}
        modalVisible={memberState}
      >
        <div>
          <Divider orientation="left">余额积分详情</Divider>
          <Descriptions>
            <Descriptions.Item label="积分产生时余额">
              {currentIntegralAccountMoney ? money_trans(currentIntegralAccountMoney, true) : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="积分产生时间">
              {currentIntegralTime ? currentIntegralTime : '暂无'}
            </Descriptions.Item>
          </Descriptions>
          <Divider orientation="left">账户信息</Divider>
          <Descriptions>
            <Descriptions.Item label="余额">
              {memberValue ? money_trans(memberValue.balance, true) : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="银行名称">
              {memberValue ? memberValue.bankName : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="银行卡号">
              {memberValue ? memberValue.bankNumber : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="积分">
              {memberValue ? memberValue.integral : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="冻结余额">
              {memberValue ? money_trans(memberValue.frozenAmount, true) : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="冻结积分">
              {memberValue ? memberValue.frozenIntegral : '暂无'}
            </Descriptions.Item>
          </Descriptions>
        </div>
      </CreateForm>

      <CreateForm
        width={800}
        title={'积分补录'}
        onCancel={() => {
          handleRepIntegralVisible(false);
        }}
        modalVisible={repIntegralVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            const hide = message.loading('正在添加');

            try {
              await repIntegra({...value, rid: repIntegralValues.id});
              hide();
              message.success('添加成功');
              handleRepIntegralVisible(false);
              return true;
            } catch (error) {
              hide();
              message.error('添加失败请重试！');
              handleRepIntegralVisible(false);
              return false;
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: '',
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
          columns={repIntegralColumns}
        />
      </CreateForm>

    </PageContainer>
  );
};

export default TableList;
